/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var ajax = require("mlib/io/ajax");

var Confirm = require("../layer/weuiconfirm");








module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;

    var loadobj = null;
    var listelem = null;
    var scrollelem = null;

    //-------------事件响应声明---------------
    var evtFuncs = {

	}

    //-------------子模块实例化---------------
    var initMod = function() { 
		custFuncs.getSync();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {

	}

    //-------------自定义函数----------------
    var custFuncs = {
            getSync:function(){
					ajax({
						url:data.requestAPIUrl,
						data: {}, 
						method: "get",
						onSuccess: function(result) {
							if(result.status==1){
								custFuncs.addCard(result.data.cards);	
							}else{
								alert(result.msg);
							}
											 				
						},
						onError: function(xmlHttp) {

						}
					});
			},
			addCard:function(cards){
				var newcards =[],curuser=null,cardids=[];
				cards.forEach(function(item,index){
					if(index==0){
						curuser=item.openid;
					}
					cardids.push(item.wxCardId);
					newcards.push({
						cardId:item.wxCardId,
						cardExt:JSON.stringify(item),
					});
				});
                //console.log("cards:",JSON.stringify(cards));
               // console.log("newcards:",JSON.stringify(newcards));
				wechat('ready',{readyfn:function(wx){
					wx.addCard({
						cardList: newcards, // 需要添加的卡券列表
						success: function (res) {
							
							var cardList = res.cardList,// 添加的卡券列表信息
								 cardObj={},
								 cardArr = []; 
							//console.log("res:",JSON.stringify(cardList));
							   cardList.forEach(function(item,index){
									if(item.isSuccess){
										if(custFuncs.in_array(item.cardId,cardids)){
											var cardExtObj = JSON.parse(item.cardExt);
											cardArr.push({
												"openid":curuser,
												"cardId":cardExtObj.cardId,
												"codeId":cardExtObj.codeId,
												"outer_str":cardExtObj.outer_str,
												"cardWeChatCode":item.code,
												"syncId":cards[index].syncId
											});
										}else{
											cardArr.push({
												"openid":curuser,
												"cardId":item.cardExt.cardId,
												"cardWeChatCode":item.code
											});
										}
                                        if(cardArr.length>0){
                                        	cardObj = cardArr[0];
                                        }
									}                            
							   });      
			   
							  // cardObj.successData = JSON.stringify(cardArr);	
							 // console.log(JSON.stringify(cardObj));		
							ajax({
								url: cards[0].requestAPIUrl,
								data: cardObj, // 仅method=post时生效，如果传入json对象会被转换成queryString，如果传入字符串则会原样发送
								method: "post", // 默认是get
								onSuccess: function (res) {
									//alert(result);
									//console.log(result.msg);
									window.location.href = res.data.detailRouter;
								},
								onError: function (xmlHttp) {
								}, // 当访问出错，比如网络连接不上、解析内容失败时触发，超时也会触发
								onTimeout: function (xmlHttp) {
								}, // 超时触发
								onAbort: function () {
								} // 网络中断时触发
							});
						},
			            fail:function(res){
			            },
			            cancel: function (res) {
			            },
					});
				}}).init();
			},
			in_array:function(needle, haystack, argStrict) { 
				  var key = ''
				  var strict = !!argStrict
				  if (strict) {
					for (key in haystack) {
					  if (haystack[key] === needle) {
						return true
					  }
					}
				  } else {
					for (key in haystack) {
					  if (haystack[key] == needle) { // eslint-disable-line eqeqeq
						return true
					  }
					}
				  }
				  return false
			} 
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};